/*
  File: PermissionService.cs
  Author: rcrxy
  CreateTime: 2025/08/06 20:50

  Description:
*/

using AutoMapper;
using Microsoft.EntityFrameworkCore;
using StudentVideo.Common.Attributes;
using StudentVideo.Common.Constants;
using StudentVideo.Common.Exceptions;
using StudentVideo.Data;
using StudentVideo.Data.Entities;
using StudentVideo.Helper;
using StudentVideo.Shared.Dtos.Permission;
using System.Threading.Tasks;

namespace StudentVideo.Services;

//TODO 权限增删改查

/// <summary>
/// 权限
/// </summary>
/// <param name="context"></param>
/// <param name="redisDb"></param>
/// <param name="mapper"></param>
public class PermissionService(AppDbContext context, RedisDbHelper redisDb, IMapper mapper) {
   private readonly AppDbContext _context = context;
   private readonly RedisDbHelper _redis = redisDb;
   private readonly IMapper _mapper = mapper;

   private readonly string[] _method = ["GET", "POST", "DELETE", "PUT"];

   /// <summary>
   /// 验证 ApiPath 格式是否正确
   /// </summary>
   /// <param name="path"></param>
   /// <returns></returns>
   private void VerifyApiPath(string path) {
      // 检查结尾是否存在 方法
      string[] paths = path.Split(':');

      var uri = paths[0];
      var method = paths[1];

      if (uri == null || method == null)
         throw new HttpException(HttpErrorMessage.PERMISSION_PATH_ERROR);


      // 检查接口方法是否合规
      if (!_method.Any(e => string.Equals(e, method, StringComparison.OrdinalIgnoreCase)))
         throw new HttpException(HttpErrorMessage.PERMISSION_PATH_ERROR);

   }

   /// <summary>
   /// 权限 - 创建
   /// </summary>
   public async Task Create(PermissionCreateRequest data) {
      VerifyApiPath(data.ApiPath);

      // 检查标识是否已存在
      var exist = await _context.Permissions.AnyAsync(e => e.Code == data.ApiPath);

      if (exist)
         throw new HttpException(HttpErrorMessage.PERMISSION_PATH_EXIST);

      PermissionEntity newData = _mapper.Map<PermissionEntity>(data);

      await _context.Permissions.AddAsync(newData);
   }

   /// <summary>
   /// 权限 - 更新
   /// </summary>
   /// <param name="data"></param>
   public async Task Update(PermissionUpdateRequest data) {
      if (data.ApiPath != null) {

         VerifyApiPath(data.ApiPath);

         var exist = await _context.Permissions.AnyAsync(e => e.Code == data.ApiPath);

         if (exist)
            throw new HttpException(HttpErrorMessage.PERMISSION_PATH_EXIST);
      }

      PermissionEntity newData = _mapper.Map<PermissionEntity>(data);


   }
}
